<template>
    <div class="container">
        <Breadcrumb :items="['menu.list', '财务报表']" />
        <a-card class="general-card" title="财务报表">
            <a-tabs default-active-key="day" type="rounded" @change="changetabs">
                <a-tab-pane key="day" title="日报"></a-tab-pane>
                <a-tab-pane key="month" title="月报"></a-tab-pane>
            </a-tabs>
            <a-row>
                <a-col>
                    <a-form :model="formData" label-align="auto" auto-label-width>
                        <a-row :gutter="16">
                            <a-col :span="12">
                                <div class="form-item">
                                    <div class="label">￥{{ totalamount.totalFee ? totalamount.totalFee : 0 }}</div>
                                    <div class="content">消费金额(元)</div>
                                </div>
                            </a-col>
                            <a-col :span="12">
                                <div class="form-item">
                                    <div class="label">{{ totalamount.totalCount ? totalamount.totalCount : 0 }}</div>
                                    <div class="content">订单数(个)</div>
                                </div>
                            </a-col>
                            <a-col :span="24">
                                <div style="width: 100%; display: flex; align-items: center; justify-content: space-between; gap: 0 10px;">
                                    <div style="width: 340px">
                                        <a-range-picker v-if="formData.granularity == 'day'" @change="onChange" @select="onSelect" style=" width: 100%; " />
                                        <a-range-picker
                                            v-else-if=" formData.granularity == 'month'"
                                            mode="month"
                                            @change="handleMonthChange"
                                            style=" width: 100%; "
                                        />
                                    </div>
                                    <a-button type="primary" status="success" style="width: 80px;" 
                                        @click="getRecordsExport(formData)">导出</a-button>
                                </div>
                                 



                            </a-col>

                        </a-row>
                    </a-form>
                </a-col>
            </a-row>

            <div style="margin-top: 20px;">
                <a-table :virtual-list-props="{ height: 460 }" :loading="loading" :columns="columns"
                    :data="tableList" :pagination="false" @page-change="onPageChange">
  <template #usedTotalAmount="{ record }">
                      {{ (record.paidTotalAmount || 0) + (record.cancelledTotalAmount || 0) > 0 ? record.usedTotalAmount || 0 : 0 }}
                    </template>
                </a-table>
            </div>

        </a-card>
    </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { recordsstats,statsByDayOrMonth } from '@/api/hairdryer'
import moment from 'moment' // 导入moment.js



let totalamount = ref({})
let amountForm = ref({
    start:'',
    end:''
})

const getrecordsstats = async () => {
    try {
       
        let res = await recordsstats(amountForm.value)
        totalamount.value = res.data


    } catch (error) {

    }
}

//时间选择器
//时间选择器
const onSelect = (dateString, date) => {
    console.log('onSelect: ', dateString, date);

    // formData.value.borrowTimeStart = '';
    // formData.value.borrowTimeEnd = '';

    // amountForm.value.start = '';
    // amountForm.value.end = '';
}
const onChange = (dateString, date) => {
    console.log('onChange: ', dateString, date);

    if (dateString) {
        formData.value.startDate = dateString[0] ;
        formData.value.endDate = dateString[1];

        amountForm.value.start = dateString[0];
        amountForm.value.end = dateString[1];
    } else {
        formData.value.startDate = '';
        formData.value.endDate = '';

        amountForm.value.start = '';
        amountForm.value.end = '';
    }

    getrecordsstats()
    getstatsByDayOrMonth()
}

//年月选择器变化处理
const handleMonthChange = (dateString) => {
    // console.log(dateString);
      if (dateString) {
        formData.value.startDate = dateString[0];
        formData.value.endDate = dateString[1];

        // 使用moment获取月份的第一天和最后一天
        const startDate = moment(dateString[0]).startOf('month').format('YYYY-MM-DD');
        const endDate = moment(dateString[1]).endOf('month').format('YYYY-MM-DD');
        
        amountForm.value.start = startDate;
        amountForm.value.end = endDate;
        
    } else {
        formData.value.startDate = '';
        formData.value.endDate = '';

        amountForm.value.start = '';
        amountForm.value.end = '';
    }

      getrecordsstats()
    getstatsByDayOrMonth()

};



//切换
const changetabs = (e) =>{
    console.log(e);
    
    formData.value.granularity = e
     formData.value.startDate = '';
        formData.value.endDate = '';
     getrecordsstats()
    getstatsByDayOrMonth()
}


let loading = ref(false);
//查询列表
let formData = ref({
    page: 1,
    size: 10,
    granularity:'day' //必填：'day' 或 'month'。示例：day=按天统计，month=按月统计,示例值(day)
})
const pagination = ref({
    "hide-on-single-page":true,
    current: formData.value.page,
    pageSize: formData.value.size, 
    showTotal: true,
    total: 0
}); // 分页属性
const columns = ref([
    {
        title: '日期',
        dataIndex: 'period',
    },
   
    {
        title: '订单总数',
        dataIndex: 'paidTotal',
    },
     {
        title: '已支付总金额',
        dataIndex: 'paidTotalAmount',
    },
   
    {
        title: '退款订单数',
        dataIndex: 'cancelledTotal',
    },
      {
        title: '退款总金额',
        dataIndex: 'cancelledTotalAmount',
    },

      {
        title: '交易笔数(含退款）',
        dataIndex: 'usedTotal',
    },
      {
        title: ' 交易金额(含退款)',
        dataIndex: 'usedTotalAmount',
        slotName: 'usedTotalAmount',
    },

])
const tableList = ref([]);
const onPageChange = (current) => {
    formData.value.page = current;
    pagination.value.current = current;
};


//获取列表

const getstatsByDayOrMonth = async ()=>{

try {
     loading.value = true
    let res = await statsByDayOrMonth(formData.value)
    tableList.value = res.data
     loading.value = false
    
} catch (error) {
     loading.value = false
    
}

   
}

// 导出表格数据函数
const getRecordsExport = (formData) => {
  if (!tableList.value || tableList.value.length == 0) {
    // 如果没有数据，可以给用户一个提示
    alert('暂无数据可导出');
    return;
  }
  
  // 准备CSV标题行（根据columns配置）
  const headers = columns.value.map(col => col.title);
  
  // 准备CSV数据行
  const rows = tableList.value.map(row => {
    return columns.value.map(col => {
      let value = '';
      
      // 处理特殊列，如usedTotalAmount需要使用插槽逻辑
      if (col.slotName === 'usedTotalAmount') {
        value = ((row.paidTotalAmount || 0) + (row.cancelledTotalAmount || 0) > 0 ? row.usedTotalAmount || 0 : 0);
      } 
      // 保持原始数据，表格显示什么就导出什么
      else if (typeof row[col.dataIndex] === 'number') {
        value = row[col.dataIndex];
      } 
      // 其他字段
      else {
        value = row[col.dataIndex] !== undefined ? row[col.dataIndex] : '';
      }
      
      // 对所有值进行CSV转义处理
      const cellValue = String(value);
      // 如果单元格包含逗号、引号或换行符，需要用引号包裹并转义内部的引号
      if (cellValue.includes(',') || cellValue.includes('"') || cellValue.includes('\n') || cellValue.includes('\r')) {
        return `"${cellValue.replace(/"/g, '""')}"`;
      }
      // 对于数字，在前面加制表符前缀确保Excel正确显示
      if (!isNaN(cellValue) && cellValue !== '' && col.dataIndex !== 'period') {
        return `\t${cellValue}`;
      }
      return cellValue;
    });
  });
  
  // 合并标题和数据行
  const csvContent = [
    headers.join(','), // 标题行
    ...rows.map(row => row.join(',')) // 数据行
  ].join('\n');
  
  // 创建Blob对象，使用Excel友好的编码和类型
  const blob = new Blob([`\uFEFF${csvContent}`], { type: 'application/vnd.ms-excel;charset=utf-8;' });
  
  // 创建下载链接
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  
  // 设置文件名，包含导出日期，使用.xlsx后缀以表示Excel格式
  const date = new Date();
  const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
  const filename = `财务报表_${formData.granularity === 'day' ? '日报' : '月报'}_${dateStr}.xlsx`;
  
  link.setAttribute('href', url);
  link.setAttribute('download', filename);
  link.style.visibility = 'hidden';
  
  // 添加到DOM并触发点击
  document.body.appendChild(link);
  link.click();
  
  // 清理
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

onMounted(() => {
    getrecordsstats()
    getstatsByDayOrMonth()
})

</script>
<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;

    .search-btn {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        gap: 0 10px;
    }


    .container-table {
        margin-top: 20px;

        .general-card {
            box-sizing: border-box;
            padding: 20px 0;


        }
    }
}


.form-item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 16px;

    .label {
        font-size: 18px;
        font-weight: bold;
    }

    .content {
        font-size: 16px;

    }
}
</style>